//
//  JKCommentViewController.m
//  Baisi
//
//  Created by albert on 16/3/26.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKCommentViewController.h"
#import "UIBarButtonItem+JKExtention.h"
#import "JKPostCell.h"
#import "JKPostModel.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "JKCommentModel.h"
#import "MJExtension.h"
#import "JKCommentHeaderView.h"
#import "JKCommentCell.h"
#import "SVProgressHUD.h"
#import "JKResponderView.h"
#import "JKVideoManager.h"

@interface JKCommentViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 所有请求的管理 */
@property (nonatomic, strong) AFHTTPSessionManager *manager;

/** 保存帖子的top_cmt */
@property (nonatomic, strong) JKCommentModel *saved_top_cmt;

/** 最热评论 */
@property (nonatomic, strong) NSArray *hotComments;
/** 最新评论 */
@property (nonatomic, strong) NSMutableArray *latestComments;

/** 最后一个评论的ID */
@property (nonatomic, assign) NSInteger currentPage;

/** 是否第一次进入评论界面 */
@property (nonatomic, assign) BOOL isFirstTime;

/** headerCell */
@property (nonatomic, weak) JKPostCell *headerCell;

/** selectCell */
@property (nonatomic, weak) JKCommentCell *selectCell;

/** 是否监听了视频下载进度 */
@property (nonatomic, assign) BOOL videoDownloadProgressKVO_added;
@end

@implementation JKCommentViewController


static NSString *commentId = @"comment";

- (AFHTTPSessionManager *)manager{
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [self.manager.operationQueue cancelAllOperations];
    
    [JKProgressHUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.bottomSpace.constant = JKCurrentHomeIndicatorHeight;
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:self.view.jk_bottomSafeAreaView.bounds];
    imgV.image = [UIImage imageNamed:@"comment-bar-bg"];
    [self.view.jk_bottomSafeAreaView addSubview:imgV];
    
    //初始化控制器
    [self setupBasic];
    
    //设置顶部标题
    [self setupHeader];
    
    //设置刷新控件
    [self setupRefresh];
    
    [JKProgressHUD showWithStatus:@"加载中..."];
    [self loadNewComments];
    
    __weak typeof(self) weakSelf = self;
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UIMenuControllerWillHideMenuNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        
        weakSelf.headerCell.contentTextLabel.backgroundColor = nil;
    }];
}

//设置刷新控件
- (void)setupRefresh{
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewComments)];
    
    //自动根据下拉比例设置透明度，未下拉时全透明
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreComments)];
    self.tableView.mj_footer.hidden = YES;
}

//设置顶部标题
- (void)setupHeader{
    //给cell包装一层view
    JKResponderView *header = [[JKResponderView alloc] init];
    header.backgroundColor = [UIColor whiteColor];//JKColor(247, 247, 247);
    
    JKPostCell *postCell = [JKPostCell viewFromXib];
    postCell.post = self.post;
    
    if (self.post.type == kPostTypeVideo) {
        
        postCell.avoidSetImage = YES;
        
        __weak typeof(self) weakSelf = self;
        
        [postCell.videoView setDownloadVideoButtonClickBlock:^(JKPostCell *cell) {
            
            [weakSelf.homeSelectCell.videoView downloadVideo];
            
            [weakSelf monitorVideoDownloadProgress];
        }];
    }
    
    //如果直接设置高度的话，因为会调用setFrame，会累加两次margin
    //所以改为设置size
    postCell.size = CGSizeMake(JKScreenW, self.post.cellHeight);
    
    [header addSubview:postCell];
    self.headerCell = postCell;
    
    [self setMoreClickAction];
    
    //不能写cell.height,只能写self.post.cellHeight，前者比后者少一个margin
    header.height = self.post.cellHeight + JKPostCellMargin;
    
    self.tableView.tableHeaderView = header;
    
    postCell.contentTextLabel.userInteractionEnabled = YES;
    [postCell.contentTextLabel addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressText:)]];
    
    [header addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCell)]];
    
    if (self.post.isDownloadingVideo) {
        
        [self monitorVideoDownloadProgress];
    }
}

- (void)monitorVideoDownloadProgress{
    
    if (_videoDownloadProgressKVO_added) {
        return;
    }
    
    _videoDownloadProgressKVO_added = YES;
    
    [self.post addObserver:self forKeyPath:@"videoDownloadProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)setMoreClickAction{
    
    if (self.post.type == kPostTypeVideo && !self.headerCell.moreClickBlock) {
        
//        __weak typeof(self) weakSelf = self;
        
        [self.headerCell setMoreClickBlock:^(JKPostCell *cell) {
            
            if ([JKVideoManager videoExistWithUrl:cell.post.videouri]) {
                
                [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)].addAction([JKAlertAction actionWithTitle:@"删除缓存视频" style:(JKAlertActionStyleDestructive) handler:^(JKAlertAction *action) {
                    
                    if ([JKVideoManager deleteVideWithUrl:cell.post.videouri]) {
                        
                        [JKProgressHUD showSuccessWithStatus:@"删除成功！"];
                        
                    }else{
                        
                        [JKProgressHUD showErrorWithStatus:@"删除失败!"];
                    }
                }]).show();
                
                return;
            }
            
            JKAlertView *alertView = [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)].addAction([JKAlertAction actionWithTitle:@"收藏" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                
            }]).addAction([JKAlertAction actionWithTitle:@"举报" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                
            }]);
            
            if (cell.post.videouri.length > 0) {
                
                alertView.addAction([JKAlertAction actionWithTitle:@"复制视频地址" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                    
                    [UIPasteboard generalPasteboard].string = cell.post.videouri;
                    
                }]);
            }
            alertView.show();
        }];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"videoDownloadProgress"]) {
        
        self.headerCell.post = self.post;
    }
}

- (void)tapCell{
    
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

- (void)longPressText:(UILongPressGestureRecognizer *)sender {
    
    if (sender.state == UIGestureRecognizerStateBegan) {
        
        [self.tableView.tableHeaderView resignFirstResponder];
        
        [self.tableView.tableHeaderView becomeFirstResponder];
        
        UIMenuController *memu = [UIMenuController sharedMenuController];
        
        // 让menu显示在cell中间
        CGRect rect = CGRectMake(0, 60, self.tableView.tableHeaderView.width, self.tableView.tableHeaderView.height * 0.5);
        
        UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyText:)];
        
        memu.menuItems = @[copy];
        
        [memu setTargetRect:rect inView:self.tableView.tableHeaderView];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [memu setMenuVisible:YES animated:YES];
            
            self.headerCell.contentTextLabel.backgroundColor = JKColor(186, 216, 243);
        });
    }
}

- (void)copyText:(UIMenuController *)menu{
    
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    board.string = self.post.text;
    [JKProgressHUD showSuccessWithStatus:@"复制成功！"];
}

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//初始化控制器
- (void)setupBasic{
    //是否第一次进入评论界面
    self.isFirstTime = YES;
    
    self.tableView.contentInset = UIEdgeInsetsMake(JKNavBarHeight, 0, 0, 0);
    
    [self.tableView jk_adapt_iOS_11_scrollView];
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(JKNavBarHeight, 0, 0, 0);
    
    //自己设置contentInset，这样方便设置第一次划到评论
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //自动计算高度
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44;
    
    //注册评论cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([JKCommentCell class]) bundle:nil] forCellReuseIdentifier:commentId];
    
    //帖子中有最热评论才需要去除，避免重复计算
    if (self.post.top_cmt) {
        //清空之前先保存，在dealloc中恢复
        self.saved_top_cmt = self.post.top_cmt;
        
        //清空top_cmt和cellHeight
        self.post.top_cmt = nil;
        [self.post setValue:@0 forKeyPath:@"cellHeight"];
    }
    
    self.title = @"评论";
    
    self.tableView.backgroundColor = JKGlobalBgColor;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"comment_nav_item_share_icon" highImage:@"comment_nav_item_share_icon_click" target:self action:@selector(shareClick)];
    
    //键盘frame将要改变时的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

//监听到键盘frame改变的方法
- (void)keyboardWillChangeFrame:(NSNotification *)noti{
    //键盘显示\隐藏完毕的frame
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //修改底部约束
    self.bottomSpace.constant = JKScreenH - frame.origin.y + (frame.origin.y == JKScreenH ? JKCurrentHomeIndicatorHeight : 0);
    //动画时间
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //动画
    [UIView animateWithDuration:duration animations:^{
        [UIView setAnimationCurve:7];
        [self.view layoutIfNeeded];
    }];
}

//加载最新评论
- (void)loadNewComments{
    //结束之前所有的请求,会调用失败的block
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.post.ID;
    params[@"hot"] = @"1";
    
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        
//        NSLog(@"%@", responseObject);
        
        //如果不是字典类型，就是没有数据，让它返回
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            [self.tableView.mj_header endRefreshing];
            return;
        }
        
        //最热评论
        self.hotComments = [JKCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"hot"]];
        
        //最新评论
        self.latestComments = [JKCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        //刷新表格！！！
        [self.tableView reloadData];
        
        NSInteger total = [responseObject[@"total"] integerValue];
        if (self.latestComments.count >= total) {
            self.tableView.mj_footer.hidden = YES;
        }
        
        //结束刷新状态
        [self.tableView.mj_header endRefreshing];
        
        //加载数据成功了才清空页码
        self.currentPage = 1;
        
        //第一次进入评论界面，直接划到评论
        if (self.isFirstTime) {
            //            [self.tableView setContentOffset:CGPointMake(0, self.tableView.tableHeaderView.height - JKNavBarHeight) animated:YES];
            //            if (self.hotComments.count > 0 || self.latestComments.count > 0) {
            //
            //                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
            //            }
            self.isFirstTime = NO;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [JKProgressHUD showErrorWithStatus:@"加载数据失败！"];
        
        //结束刷新状态
        [self.tableView.mj_header endRefreshing];
    }];
}

//加载更多评论
- (void)loadMoreComments{
    //结束之前所有的请求,会调用失败的block
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //当前页
    NSInteger currentPage = self.currentPage + 1;
    
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"dataList";
    params[@"c"] = @"comment";
    params[@"data_id"] = self.post.ID;
    params[@"lastcid"] = [self.latestComments.lastObject ID];
    params[@"page"] = @(currentPage);
    
    //发送请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"%@", responseObject);
        
        //如果不是字典类型，就是没有数据，让它返回
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            self.tableView.mj_footer.hidden = YES;
            return;
        }
        
        //最新评论
        NSArray *moreComments = [JKCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [self.latestComments addObjectsFromArray:moreComments];
        
        //刷新表格！！！
        [self.tableView reloadData];
        
        NSInteger total = [responseObject[@"total"] integerValue];
        if (self.latestComments.count >= total) {//全部加载完毕
            self.tableView.mj_footer.hidden = YES;
        }else{
            //结束刷新状态
            [self.tableView.mj_footer endRefreshing];
        }
        
        //加载成功才设置页码
        self.currentPage = currentPage;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [JKProgressHUD showErrorWithStatus:@"加载数据失败！"];
        
        //结束刷新状态
        [self.tableView.mj_footer endRefreshing];
    }];
}

//点击导航条右上角三个点
- (void)shareClick {
    
}

//添加了通知一定要记得移除
- (void)dealloc{
    
    NSLog(@"%d, %s",__LINE__, __func__);
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if (_videoDownloadProgressKVO_added) {
        
        [self.post removeObserver:self forKeyPath:@"videoDownloadProgress"];
    }
    
    //如果保存的有值的话才需要恢复
    if (self.saved_top_cmt) {
        //恢复模型数据
        self.post.top_cmt = self.saved_top_cmt;
        //高度不清零的话，最热评论会盖住帖子内容
        [self.post setValue:@0 forKeyPath:@"cellHeight"];
    }
    
    //取消所有操作
    //1. [self.manager.operationQueue cancelAllOperations];
    //2. [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    [self.manager invalidateSessionCancelingTasks:YES];
}

#pragma mark - <UITableViewDataSource>
//组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger hotCount = self.hotComments.count;
    NSInteger latestCount = self.latestComments.count;
    
    if (hotCount) return 2; //有最热评论 + 最新 = 2组
    if (latestCount) return 1; //只有最新 = 1组
    
    return 0; //没有评论 = 0组
}

//每一组的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger hotCount = self.hotComments.count;
    NSInteger latestCount = self.latestComments.count;
    
    //xib加载的tableView并不会直接调用这里
    self.tableView.mj_footer.hidden = (latestCount == 0);
    
    if (section == 0) {
        return hotCount ? hotCount : latestCount;
    }
    
    //非第0组
    return latestCount;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    JKCommentHeaderView *header = [JKCommentHeaderView headerViewWithTableView:tableView];
    
    //设置文字
    NSInteger hotCount = self.hotComments.count;
    if (section == 0) {//第0组
        header.headerTitle = hotCount ? @"最热评论" : @"最新评论";
    }else{//非第0组
        header.headerTitle = @"最新评论" ;
    }
    
    return header;
}

//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JKCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:commentId];
    
    cell.comment = [self commentInIndexPath:indexPath];
    
    return cell;
}

/** 返回第section组的所有评论数组 */
- (NSArray *)commentsInSection:(NSInteger)section{
    if (section == 0) {
        return self.hotComments.count ? self.hotComments : self.latestComments;
    }
    return self.latestComments;
}

/** 返回对应组的模型 */
- (JKCommentModel *)commentInIndexPath:(NSIndexPath *)indexPath{
    return [self commentsInSection:indexPath.section][indexPath.row];
}

#pragma mark - <UITableViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    
    //隐藏menu
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //UIMenuController
    UIMenuController *menu = [UIMenuController sharedMenuController];
    
    //如果menu已经显示了，再次点击要隐藏
    if (menu.isMenuVisible) {
        //隐藏menu
        [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
        return;
    }
    
    //取出选中的cell
    JKCommentCell *cell = (JKCommentCell *)[tableView cellForRowAtIndexPath:indexPath];
    self.selectCell = cell;
    
    //让cell成为第一响应者。只要卸任第一响应者，menu就会消失
    [cell becomeFirstResponder];
    
    //自定义item
    UIMenuItem *ding = [[UIMenuItem alloc] initWithTitle:@"顶" action:@selector(ding:)];
    UIMenuItem *respond = [[UIMenuItem alloc] initWithTitle:@"回复" action:@selector(respond:)];
    UIMenuItem *report = [[UIMenuItem alloc] initWithTitle:@"举报" action:@selector(report:)];
    UIMenuItem *copyComment = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyComment:)];
    menu.menuItems = [cell.comment.content isEqualToString:@""] ? @[ding, respond, report] : @[ding, respond, report, copyComment];
    
    //让menu显示在cell中间
    CGRect rect = CGRectMake(0, 40, cell.width, cell.height * 0.5);
    [menu setTargetRect:rect inView:cell];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [menu setMenuVisible:YES animated:YES];
    });
}

#pragma mark - UIMenuController点击处理
- (void)copyComment:(UIMenuController *)menu{
    
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    board.string = self.selectCell.comment.content;
    [JKProgressHUD showSuccessWithStatus:@"复制成功！"];
}

//顶
- (void)ding:(UIMenuController *)menu{
    //NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    //JKLog(@"%s %@", __func__, [self commentInIndexPath:indexPath].content);
}

//回复
- (void)respond:(UIMenuController *)menu{
    //获取选中的行
    //NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    //获取选中行对应的模型，取得“顶、回复、举报”的内容
    //JKCommentModel *comment = [self commentInIndexPath:indexPath];
    //JKLog(@"%s %@", __func__, comment.content);
}

//举报
- (void)report:(UIMenuController *)menu{
    //NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    //JKLog(@"%s %@", __func__, [self commentInIndexPath:indexPath].content);
}
@end
